<template>
  <el-card shadow="hover">
    <template #header>
      <div class="card-header">
        <el-tabs v-model="activeTab" type="card" @tab-click="handleTabChange">
          <el-tab-pane label="销售统计" name="sales"></el-tab-pane>
          <el-tab-pane label="采购统计" name="purchase"></el-tab-pane>
        </el-tabs>
        <div class="time-filter">
          <el-radio-group v-model="timeRange" @change="handleTimeChange">
            <el-radio label="week">最近1周</el-radio>
            <el-radio label="month">最近30天</el-radio>
            <el-radio label="year" v-model="timeRange" style="color: #409EFF;">最近1年</el-radio>
          </el-radio-group>
        </div>
      </div>
    </template>
    <div class="chart-container">
      <canvas ref="chartRef"></canvas>
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { Chart, registerables } from 'chart.js'
Chart.register(...registerables)

const chartRef = ref(null)
const activeTab = ref('sales')
const timeRange = ref('year')
let chartInstance = null

const salesData = {
  months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  orderAmount: [100, 500, 100, 70, 300, 200, 450, 250, 500, 10, 300, 550],
  orderCount: [150, 120, 200, 550, 400, 100, 500, 450, 300, 180, 500, 280]
}

const initChart = () => {
  nextTick(() => {
    if (chartInstance) chartInstance.destroy()
    const ctx = chartRef.value.getContext('2d')
    chartInstance = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: salesData.months,
        datasets: [
          {
            label: '订单额',
            data: salesData.orderAmount,
            type: 'bar',
            backgroundColor: '#409EFF',
            yAxisID: 'y'
          },
          {
            label: '订单数',
            data: salesData.orderCount,
            type: 'line',
            borderColor: '#67C23A',
            yAxisID: 'y1'
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
          y: {
            beginAtZero: true,
            title: { display: true, text: '单位(元)' }
          },
          y1: {
            beginAtZero: true,
            position: 'right',
            title: { display: true, text: '单位(笔)' },
            grid: { drawOnChartArea: false }
          }
        }
      }
    })
  })
}

const handleTabChange = (tab) => {
  activeTab.value = tab.name
  initChart()
}

const handleTimeChange = () => {
  initChart()
}

onMounted(() => {
  initChart()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.time-filter {
  display: flex;
  gap: 8px;
}
.chart-container {
  width: 100%;
  height: 300px;
}
</style>